<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表格区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-button type="primary" @click="addRoleBtn">添加角色</el-button>
      </el-row>
      <!-- 角色列表内容 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'aic']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'aic']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editBtn(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-delete"
              @click="deleteBtn(scope.row)"
              >删除</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-setting"
              @click="privilegesBtn(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限弹出框  -->
    <el-dialog
      title="分配权限"
      :visible.sync="privilegesVisible"
      width="50%"
      :before-close="privilegesVisibleClose"
    >
      <!-- 树形区域 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="treeKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="privilegesVisible = false">取 消</el-button>
        <el-button type="primary" @click="authorizationBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editVisible"
      width="50%"
      @close="resetEditForm"
    >
      <!-- 表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleVisible"
      width="50%"
      @close="addRoleFormClose"
    >
      <!-- 表单 -->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入API
import {
  getRolesApi,
  getRemoveRightsApi,
  getRightListApi,
  getAuthorizationApi,
  getEditRoleApi,
  getRoleIDApi,
  getDeleteRoleApi,
  getAddRoleApi
} from '@/api/rights.js'
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 显示隐藏分配权限框
      privilegesVisible: false,
      // 权限列表数据
      rightList: [],
      // 树形数据对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树形区域默认勾选的id
      treeKey: [],
      // 分配权限的角色id
      roleId: 0,
      // 编辑对话框的表单数据对象
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      // 控制编辑对话框的显示与隐藏
      editVisible: false,
      // 当前编辑角色的ID
      editRoleId: 0,
      // 编辑对话框里的表单效验
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制添加角色对话框显示与隐藏
      addRoleVisible: false,
      // 添加角色对话框的表单双向绑定数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加对话框里的表单效验
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用角色列表数据
    this.getRolesApi()
  },
  methods: {
    // 封装获取角色列表数据
    getRolesApi() {
      getRolesApi().then((res) => {
        if (res.data.meta.status === 200) {
          this.rolesList = res.data.data
          this.$message.success('获取角色列表成功')
        } else {
          this.$message.error('获取角色列表失败')
        }
      })
    },
    // 封装编辑角色请求
    getEditRoleApi() {
      getEditRoleApi(this.editRoleId, this.editForm).then((res) => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message.success('编辑角色成功')
        // 更新页面
        this.getRolesApi()
      })
    },
    // 封装根据ID查询角色详细信息
    getRoleIDApi(id) {
      getRoleIDApi(id).then((res) => {
        // 赋值
        this.editForm.roleName = res.data.data.roleName
        this.editForm.roleDesc = res.data.data.roleDesc
        this.editRoleId = res.data.data.roleId
      })
    },
    // 封装删除角色请求
    getDeleteRoleApi(id) {
      getDeleteRoleApi(id).then((res) => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        // 刷新页面
        this.getRolesApi()
      })
    },
    // 封装添加角色请求
    getAddRoleApi() {
      getAddRoleApi(this.addRoleForm).then(res => {
        if (res.data.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 刷新页面
        this.getRolesApi()
      })
    },
    // 根据id删除权限
    removeRightsById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          getRemoveRightsApi({
            roleId: role.id,
            rightId
          }).then((res) => {
            if (res.data.meta.status === 200) {
              // 更新页面最新数据
              role.children = res.data.data
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          })
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    // 分配权限框点X关闭
    privilegesVisibleClose() {
      this.privilegesVisible = false
    },
    // 分配权限显示弹出框
    privilegesBtn(role) {
      // 清空数组
      this.treeKey = []
      // 角色的id
      this.roleId = role.id
      getRightListApi().then((res) => {
        if (res.data.meta.status === 200) {
          this.rightList = res.data.data
          // 调用递归获取的三级权限id
          this.getTreeKey(role, this.treeKey)
          this.privilegesVisible = true
          this.$message.success('获取权限列表成功')
        } else {
          this.$message.error('获取权限列表失败')
        }
      })
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到treeKey数组中
    getTreeKey(node, arr) {
      // 如果当前的node节点不包含children树形,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach((item) => this.getTreeKey(item, arr))
    },
    // 点击确定按钮并角色授权
    authorizationBtn() {
      // 获取选择的权限id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ].join(',')
      // 请求
      getAuthorizationApi(this.roleId, { rids: keys }).then(() => {
        // 更新权限列表
        getRolesApi().then((res) => {
          if (res.data.meta.status === 200) {
            this.rolesList = res.data.data
            this.$message.success('分配成功')
          }
        })
        // 关闭弹出框
        this.privilegesVisible = false
      })
    },
    // 点击编辑按钮触发
    editBtn(row) {
      // 调用根据id查询角色详细信息请求
      this.getRoleIDApi(row.id)
      // 显示对话框
      this.editVisible = true
    },
    // 确定提交编辑角色触发
    editSubmit() {
      // 调用编辑角色请求
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        this.getEditRoleApi()
        // 关闭对话框
        this.editVisible = false
      })
    },
    // 重置编辑角色表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除角色按钮触发
    deleteBtn(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除角色请求
          this.getDeleteRoleApi(row.id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击添加角色按钮触发
    addRoleBtn() {
      this.addRoleVisible = true
    },
    // 添加角色对话框确定提交触发
    addRoleSubmit() {
      this.$refs.addRoleFormRef.validate(valid => {
        if (!valid) return
        // 调用添加角色请求
        this.getAddRoleApi()
        // 关闭对话框
        this.addRoleVisible = false
      })
    },
    // 添加对话框关闭触发重置表单
    addRoleFormClose() {
      this.$refs.addRoleFormRef.resetFields()
    }
  }
}
</script>

<style lang='less' scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
// 居中
.aic {
  display: flex;
  align-items: center;
}
</style>
